<template>
  <div class="my-appointments-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <h2>我的预约</h2>
          <el-button type="primary" @click="$router.push('/appointment')">
            <el-icon><Plus /></el-icon>
            新建预约
          </el-button>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="预约状态">
            <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
              <el-option label="已预约" :value="1" />
              <el-option label="已完成" :value="2" />
              <el-option label="已取消" :value="0" />
              <el-option label="已过期" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadAppointments">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 预约列表 -->
      <div class="appointments-list">
        <div 
          v-for="appointment in appointments" 
          :key="appointment.id"
          class="appointment-card"
          :class="getStatusClass(appointment.status)"
        >
          <div class="appointment-header">
            <div class="appointment-info">
              <h3>{{ appointment.storeManagerName }}</h3>
              <div class="appointment-meta">
                <el-tag :type="getStatusTagType(appointment.status)" size="small">
                  {{ appointment.statusName }}
                </el-tag>
                <span class="service-type">{{ appointment.serviceType }}</span>
              </div>
            </div>
            <div class="appointment-actions">
              <el-button 
                v-if="appointment.status === 1 && canCancel(appointment)"
                size="small" 
                type="warning" 
                @click="cancelAppointment(appointment)"
              >
                取消预约
              </el-button>
              <el-button 
                size="small" 
                type="primary" 
                text
                @click="viewAppointmentDetail(appointment)"
              >
                查看详情
              </el-button>
            </div>
          </div>
          
          <div class="appointment-details">
            <div class="detail-item">
              <el-icon><Calendar /></el-icon>
              <span>预约日期：{{ formatDate(appointment.appointmentDate) }}</span>
            </div>
            <div class="detail-item">
              <el-icon><Clock /></el-icon>
              <span>预约时间：{{ appointment.appointmentTime }}</span>
            </div>
            <div v-if="appointment.remark" class="detail-item">
              <el-icon><Document /></el-icon>
              <span>备注：{{ appointment.remark }}</span>
            </div>
            <div class="detail-item">
              <el-icon><Timer /></el-icon>
              <span>创建时间：{{ formatDateTime(appointment.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="appointments.length === 0" description="暂无预约记录">
        <el-button type="primary" @click="$router.push('/appointment')">
          立即预约
        </el-button>
      </el-empty>
    </el-card>

    <!-- 预约详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="预约详情"
      width="500px"
    >
      <div v-if="selectedAppointment" class="appointment-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="理发师">
            {{ selectedAppointment.storeManagerName }}
          </el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag :type="getStatusTagType(selectedAppointment.status)">
              {{ selectedAppointment.statusName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">
            {{ formatDate(selectedAppointment.appointmentDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ selectedAppointment.appointmentTime }}
          </el-descriptions-item>
          <el-descriptions-item label="服务类型">
            {{ selectedAppointment.serviceType }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedAppointment.remark" label="备注">
            {{ selectedAppointment.remark }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(selectedAppointment.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedAppointment.updateTime !== selectedAppointment.createTime" label="更新时间">
            {{ formatDateTime(selectedAppointment.updateTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="selectedAppointment && selectedAppointment.status === 1 && canCancel(selectedAppointment)"
            type="warning" 
            @click="cancelAppointmentFromDetail"
          >
            取消预约
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Calendar, Clock, Document, Timer } from '@element-plus/icons-vue'
import { getMyAppointments, cancelAppointment as cancelAppointmentApi } from '@/api/appointment'

// 响应式数据
const appointments = ref([])
const detailDialogVisible = ref(false)
const selectedAppointment = ref(null)

// 筛选表单
const filterForm = reactive({
  status: null
})

// 页面加载时获取数据
onMounted(() => {
  loadAppointments()
})

// 加载预约列表
const loadAppointments = async () => {
  try {
    const response = await getMyAppointments()
    if (response.code === 200) {
      let data = response.data
      
      // 根据状态筛选
      if (filterForm.status !== null) {
        data = data.filter(item => item.status === filterForm.status)
      }
      
      appointments.value = data
    } else {
      ElMessage.error(response.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
  }
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.status = null
  loadAppointments()
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusClasses = {
    0: 'status-cancelled',
    1: 'status-booked',
    2: 'status-completed',
    3: 'status-expired'
  }
  return statusClasses[status] || ''
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const tagTypes = {
    0: 'info',
    1: 'success',
    2: 'primary',
    3: 'warning'
  }
  return tagTypes[status] || 'info'
}

// 检查是否可以取消预约
const canCancel = (appointment) => {
  if (appointment.status !== 1) return false
  
  const appointmentDateTime = new Date(`${appointment.appointmentDate} ${appointment.appointmentHour}:00:00`)
  const now = new Date()
  const oneHourBefore = new Date(appointmentDateTime.getTime() - 60 * 60 * 1000)
  
  return now < oneHourBefore
}

// 取消预约
const cancelAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个预约吗？取消后不可恢复。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await cancelAppointmentApi(appointment.id)
    if (response.code === 200) {
      ElMessage.success('预约已取消')
      loadAppointments()
    } else {
      ElMessage.error(response.message || '取消预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败')
    }
  }
}

// 查看预约详情
const viewAppointmentDetail = (appointment) => {
  selectedAppointment.value = appointment
  detailDialogVisible.value = true
}

// 从详情对话框取消预约
const cancelAppointmentFromDetail = async () => {
  await cancelAppointment(selectedAppointment.value)
  detailDialogVisible.value = false
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.my-appointments-container {
  padding: 20px;
}

.page-card {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.appointments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.appointment-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
  transition: all 0.3s;
}

.appointment-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.appointment-card.status-booked {
  border-left: 4px solid #67c23a;
}

.appointment-card.status-completed {
  border-left: 4px solid #409eff;
}

.appointment-card.status-cancelled {
  border-left: 4px solid #909399;
}

.appointment-card.status-expired {
  border-left: 4px solid #e6a23c;
}

.appointment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.appointment-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.appointment-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.service-type {
  color: #606266;
  font-size: 14px;
}

.appointment-actions {
  display: flex;
  gap: 8px;
}

.appointment-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.detail-item .el-icon {
  color: #909399;
}

.appointment-detail {
  margin: 16px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-appointments-container {
    padding: 12px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .appointment-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .appointment-actions {
    justify-content: flex-start;
  }
  
  .filter-section .el-form {
    flex-direction: column;
  }
  
  .filter-section .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
}
</style> 